package com.fitbet.api.service.impl;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.demo2do.core.persistence.GenericDaoSupport;
import com.demo2do.core.persistence.annotation.Dao;
import com.demo2do.core.utils.JsonUtils;
import com.fitbet.api.dao.UserDao;
import com.fitbet.api.service.UserService;
import com.fitbet.entity.user.User;

/**
 * 
 * @author dan
 *
 */
@Service("userService")
public class UserServiceImpl implements UserService{
    
    private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
    
    @Autowired
    private GenericDaoSupport genericDaoSupport;
    
    @Dao
    private UserDao userDao; 
    
    /*
     * (non-Javadoc)
     * @see com.fitbet.api.service.UserService#load(java.lang.Long)
     */
    public User load(Long userId) {
        return genericDaoSupport.load(User.class, userId);
    }
    
    /*
     * (non-Javadoc)
     * @see com.fitbet.api.service.UserService#loadUser(java.lang.String)
     */
    public User loadUser(String unionid) {
        return userDao.load(unionid);
    }
    
    /*
     * (non-Javadoc)
     * @see com.fitbet.api.service.UserService#create(java.lang.String, java.lang.String, java.lang.String, java.lang.String)
     */
    public User create(String unionid, String nickname, String avatar, String openid) {
        
        logger.trace("create user ... ");
        
        User user = null;
        
        // 1. create user when it is new
        if(StringUtils.isNotBlank(unionid)) {
            user = userDao.load(unionid);
        }
        
        logger.trace("current user is [{}]", JsonUtils.toJson(user));
        
        if(user == null) {  // when user does not exist, create a new one
                
            user = new User(unionid, openid, null);

            // update user's nickname, avatar
            genericDaoSupport.save(user.initliaze(nickname, avatar));
        }
            
        genericDaoSupport.update(user.initliaze(nickname, avatar));
            
        return user;
        
    }
}
